# -*- coding: utf-8 -*-
# main.py
"""
Smart AI Chat 主程序入口
"""

import streamlit as st
import asyncio
import sys
import os
from pathlib import Path

# 添加项目路径到系统路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

# 页面配置
st.set_page_config(
    page_title="Smart AI Chat",
    page_icon="🤖",
    layout="wide",
    initial_sidebar_state="expanded",
    menu_items={
        'Get Help': 'https://github.com/your-repo/smart-ai-chat',
        'Report a bug': 'https://github.com/your-repo/smart-ai-chat/issues',
        'About': """
        # Smart AI Chat v2.0
        
        智能AI群聊系统 - 让多个AI模型协同为您服务！
        
        🚀 **核心特性:**
        - 多AI模型并行对话
        - 智能回答整合
        - 本地数据存储
        - 美观现代界面
        
        Made with ❤️ by AI Developer Team
        """
    }
)

# CSS样式
st.markdown("""
<style>
    /* 隐藏Streamlit默认元素 */
    #MainMenu {visibility: hidden;}
    footer {visibility: hidden;}
    header {visibility: hidden;}
    
    /* 自定义聊天消息样式 */
    .chat-message {
        padding: 1rem;
        margin: 0.5rem 0;
        border-radius: 10px;
        max-width: 80%;
        word-wrap: break-word;
    }
    
    .user-message {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        margin-left: auto;
    }
    
    .assistant-message {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        color: white;
        margin-right: auto;
    }
    
    /* 模型徽章样式 */
    .model-badge {
        display: inline-block;
        padding: 0.25rem 0.5rem;
        border-radius: 15px;
        font-size: 0.8rem;
        font-weight: bold;
        margin: 0.2rem;
    }
    
    /* 侧边栏样式 */
    .sidebar .sidebar-content {
        background: linear-gradient(180deg, #667eea 0%, #764ba2 100%);
        color: white;
    }
    
    /* 主要按钮样式 */
    .stButton > button {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border: none;
        border-radius: 20px;
        padding: 0.5rem 1rem;
        font-weight: bold;
        transition: transform 0.2s;
    }
    
    .stButton > button:hover {
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(0,0,0,0.2);
    }
    
    /* 指标卡片样式 */
    .metric-card {
        background: white;
        padding: 1rem;
        border-radius: 10px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        border-left: 4px solid #667eea;
    }
    
    /* 加载动画 */
    .loading-spinner {
        border: 4px solid #f3f3f3;
        border-top: 4px solid #667eea;
        border-radius: 50%;
        width: 40px;
        height: 40px;
        animation: spin 1s linear infinite;
        margin: 20px auto;
    }
    
    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
    
    /* 响应式设计 */
    @media (max-width: 768px) {
        .chat-message {
            max-width: 95%;
        }
    }
</style>
""", unsafe_allow_html=True)

def initialize_session_state():
    """初始化会话状态"""
    
    # 基础状态
    if "initialized" not in st.session_state:
        st.session_state.initialized = True
        st.session_state.current_page = "💬 智能对话"
        st.session_state.chat_history = []
        st.session_state.conversation_id = None
        st.session_state.selected_models = ["gpt-4"]
        st.session_state.temperature = 0.7
        st.session_state.max_tokens = 2000
        st.session_state.stream_response = True
        st.session_state.auto_save = True
        st.session_state.system_prompt = ""
        st.session_state.api_keys = {}
        st.session_state.total_conversations = 0
        st.session_state.total_messages = 0
        st.session_state.show_examples = False
        st.session_state.theme = "浅色主题"
        st.session_state.language = "简体中文"
        st.session_state.font_size = "中"
        st.session_state.show_timestamps = True
        st.session_state.show_model_badges = True
        st.session_state.compact_mode = False
        st.session_state.enable_sound = False
        st.session_state.sound_volume = 50
        st.session_state.max_history = 100
        st.session_state.request_timeout = 60
        st.session_state.auto_save_interval = 5
        st.session_state.max_concurrent_requests = 3
        st.session_state.enable_encryption = False
        st.session_state.debug_mode = False

        from config.settings import load_api_keys
        st.session_state.api_keys = load_api_keys()

        # 尝试加载已保存的API密钥
        # try:
        #     from config.settings import load_api_keys
        #     # from config.settings import load_api_keys
        #     st.session_state.api_keys = load_api_keys()
        # except:
        #     print("在config无法加载保存的API秘钥")


def load_required_modules():
    """加载必要的模块"""
    try:
        # 尝试导入关键模块
        import streamlit as st
        return True
    except ImportError as e:
        st.error(f"❌ 缺少必要的依赖包: {e}")
        st.info("请运行: pip install -r requirements.txt")
        return False

def check_environment():
    """检查运行环境"""
    issues = []
    
    # 检查Python版本
    if sys.version_info < (3, 8):
        issues.append("❌ Python版本过低，需要3.8+")
    
    # 检查必要目录
    required_dirs = ["data", "data/conversations", "data/config"]
    for dir_path in required_dirs:
        Path(dir_path).mkdir(parents=True, exist_ok=True)
    
    # 检查必要文件
    required_files = ["config/settings.py", "frontend/components/__init__.py"]
    for file_path in required_files:
        if not Path(file_path).exists():
            issues.append(f"❌ 缺少必要文件: {file_path}")
    
    return issues

def main():
    """主程序入口"""
    
    # 检查环境
    issues = check_environment()
    if issues:
        st.error("环境检查失败:")
        for issue in issues:
            st.error(issue)
        st.stop()
    
    # 加载模块
    if not load_required_modules():
        st.stop()
    
    # 初始化会话状态
    initialize_session_state()
    
    # 显示页面标题
    st.title("🤖 Smart AI Chat - 智能AI群聊系统")
    st.markdown("---")
    
    # 检查是否有API密钥
    if not st.session_state.get("api_keys"):
        st.warning("⚠️ 欢迎使用Smart AI Chat！请先配置API密钥以开始使用。")
        st.info("💡 请在侧边栏的系统设置中配置您的API密钥")
    
    try:
        # 导入页面组件
        from frontend.components.sidebar import render_sidebar
        from frontend.pages.chat import render_chat_page
        from frontend.pages.settings import render_settings_page
        from frontend.pages.analytics import render_analytics_page
        
        # 渲染侧边栏
        current_page = render_sidebar()
        st.session_state.current_page = current_page
        
        # 根据选择的页面渲染内容
        if current_page == "💬 智能对话":
            render_chat_page()
        elif current_page == "⚙️ 系统设置":
            render_settings_page()
        elif current_page == "📊 数据分析":
            render_analytics_page()
        else:
            st.error(f"未知页面: {current_page}")
            
    except ImportError as e:
        st.error(f"❌ 导入模块失败: {e}")
        st.info("请确保所有必要的文件都已创建")
        
        # 显示调试信息
        if st.session_state.get("debug_mode"):
            st.code(f"错误详情: {str(e)}")
            st.code(f"Python路径: {sys.path}")
            st.code(f"当前目录: {os.getcwd()}")
    
    except Exception as e:
        st.error(f"❌ 应用启动失败: {e}")
        
        # 显示调试信息
        if st.session_state.get("debug_mode"):
            import traceback
            st.code(traceback.format_exc())

if __name__ == "__main__":
    main()